<?

/**
 * Controller class
 *
 * @author
 * @version 1.0
*/
class Controller extends Core {

	function __construct () {
		parent::__construct();
	}

	public function browse ($options, $params = null) {
		
		// Get the items
		$model = $this->load->model($options);
		$data = $model->browse($params);
	
		// Render
		$this->load->view('browse', $data);
		
	}

	public function details ($options, $params = null) {

		// Get ID
		define("ID", current($params["id"]));
		$model = $this->load->model($options);
		$data = $model->details(ID);

		// Render
		$this->load->view('details', $data);
		
	}
	
	public function edit ($options, $params = null) {

		// Prepare object
		$model = $this->load->model($options);
		
		// Check ID
		if ($params["id"])
			$id = current($params["id"]);
	
		// Form for updating items
		if ($id) {
			$data = $model->edit($id);	
			$form = 'update';
			$api = $data;
		}
		// Creating items
		else {
			$form = 'add';
			$data['data'][0] = array();
			$e = $model->columns('edit', $object);
			$data['info']['columns'] = $e['fieldset'];
		}
		
		// Get the key
		$key = $model->options['key'];
		
		// Render
		$this->load->view('edit', $data);
		
	}
	
	
	public function add ($options, $params = null, $data = null) {
	
		// Prepare object
		$model = $this->load->model($options);
		
		// Order the received data
		foreach($data as $name => $field) {
			foreach ($field as $key => $value) {
				$selected[$key][$name] = $value;
			}
		}
		// Add each one
		foreach ($selected as $id => $data) {
			$results[] = $model->add($data);
		}
		
		// Redirect
		$state = $this->session->get('list-' . $options["table"]);
		header("Location: " . URL . $state["url"]);
		
	}
	
	public function update ($options, $params = null, $data = null) {
	
		// Prepare object
		$model = $this->load->model($options);
		
		// Order the received data
		foreach($data as $name => $field) {
			foreach ($field as $key => $value) {
				$selected[$key][$name] = $value;
			}
		}
		// Update each one
		foreach ($selected as $id => $data) {
			if ($id) {
				$results[] = $model->update($id, $data);
			}
		}
		
		// Redirect
		$state = $this->session->get('list-' . $options["table"]);
		header("Location: " . URL . $state["url"]);
		
	}
	
	public function delete ($options, $params = null, $data = null) {
	
		// Prepare object
		$model = $this->load->model($options);
			
		// Check ID
		if ($params["id"]) {
			foreach ($params["id"] as $value) {
				$results[] = $model->remove($value);
			}
		}
		
		// Redirect
		$state = $this->session->get('list-' . $options["table"]);
		header("Location: " . URL . $state["url"]);
		
	}

}

?>